package org.iartisan.thought.server.service.handler;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.iartisan.thought.server.service.bo.UserMessageBO;
import org.iartisan.thought.server.service.management.UserMessageManagementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.StringWriter;

/**
 * <p>
 * 消息处理
 *
 * @author King
 * @since 2018/2/1
 */
@Service
public class MessageHandler {

    @Autowired
    private Configuration configuration;

    private static Template welcomeTemplate;

    private static Template commentTemplate;

    private static final String welcome_msg_location = "welcome_msg.ftl";

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserMessageManagementService userMessageManagementService;

    private Template getWelcomeTemplate() throws IOException {
        if (null == welcomeTemplate) {
            welcomeTemplate = configuration.getTemplate(welcome_msg_location);
        }
        return welcomeTemplate;
    }

    private Template getCommentTemplate() throws IOException {
        if (null == commentTemplate) {
            commentTemplate = configuration.getTemplate("");
        }
        return commentTemplate;
    }

    /**
     * 欢迎消息
     */
    public void sendWelcomeMsg(String userId) {
        StringWriter writer = new StringWriter();
        try {
            getWelcomeTemplate().process(null, writer);
            String message = writer.toString();
            UserMessageBO messageBO = new UserMessageBO();
            messageBO.setContent(message);
            messageBO.setFromUser("system");
            messageBO.setToUser(userId);
            userMessageManagementService.saveData(messageBO);
        } catch (Exception e) {
            logger.error("sendWelcomeMsg",e);
        }
    }

    /**
     * 贴子回复消息
     */
    public void commentMsg() {
        StringWriter writer = new StringWriter();
        try {
            getCommentTemplate().process(null, writer);
            String message = writer.toString();
        } catch (Exception e) {

        }
    }
}
